// LocationManager.m
#import "LocationManager.h"

@interface LocationManager ()

@property (strong, nonatomic) CLLocationManager *locationManager;
@property (copy, nonatomic) LocationSuccessHandler successHandler;
@property (copy, nonatomic) LocationFailureHandler failureHandler;

@end

@implementation LocationManager

+ (instancetype)sharedManager {
    static LocationManager *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        _locationManager.distanceFilter = kCLDistanceFilterNone;
    }
    return self;
}

- (void)getCurrentLocationWithSuccess:(LocationSuccessHandler)success
                             failure:(LocationFailureHandler)failure {
    self.successHandler = success;
    self.failureHandler = failure;
    
    // 检查定位权限
    CLAuthorizationStatus status = [LocationManager locationAuthorizationStatus];
    
    if (status == kCLAuthorizationStatusDenied || status == kCLAuthorizationStatusRestricted) {
        // 用户已拒绝或受限
        NSError *error = [NSError errorWithDomain:@"LocationService"
                                             code:-1
                                         userInfo:@{NSLocalizedDescriptionKey: @"定位服务被禁用，请前往设置开启"}];
        if (self.failureHandler) {
            self.failureHandler(error);
        }
        return;
    }
    
    // 请求权限（如果尚未确定）
    if (status == kCLAuthorizationStatusNotDetermined) {
        if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [_locationManager requestWhenInUseAuthorization];
        }
        return;
    }
    
    // 开始定位
    [_locationManager startUpdatingLocation];
}

+ (CLAuthorizationStatus)locationAuthorizationStatus {
    return [CLLocationManager authorizationStatus];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations {
    // 获取最新位置
    CLLocation *location = [locations lastObject];
    
    // 停止定位以节省电量
    [_locationManager stopUpdatingLocation];
    
    // 返回结果
    if (self.successHandler) {
        self.successHandler(location.coordinate);
    }
    
    // 清空回调
    self.successHandler = nil;
    self.failureHandler = nil;
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    // 停止定位
    [_locationManager stopUpdatingLocation];
    
    // 返回错误
    if (self.failureHandler) {
        self.failureHandler(error);
    }
    
    // 清空回调
    self.successHandler = nil;
    self.failureHandler = nil;
}

- (void)locationManager:(CLLocationManager *)manager
didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    // 当权限状态变化时，如果已授权则开始定位
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse ||
        status == kCLAuthorizationStatusAuthorizedAlways) {
        [_locationManager startUpdatingLocation];
    } else if (status == kCLAuthorizationStatusDenied) {
        if (self.failureHandler) {
            NSError *error = [NSError errorWithDomain:@"LocationService"
                                                 code:-1
                                             userInfo:@{NSLocalizedDescriptionKey: @"用户拒绝定位权限"}];
            self.failureHandler(error);
        }
    }
}

@end
